<template>
  <page-layout class="task">
    <div class="search-wrapper">
      <div>
        <a-input
          placeholder="请输入任务名称"
          class="search-input"
          v-model="searchText"
        >
          <a-icon
            slot="prefix"
            type="search"
            style="font-size: 28px; color: #999"
          />
        </a-input>
        <a-button type="primary" class="search-button" @click="handelsearch"
          >搜索</a-button
        >
      </div>
      <a-button
        v-if='userInfo.permissions.task_insert'
        style="width: 120px; height: 54px"
        type="primary"
        @click="
          $router.push({
            path: '/task/add',
            query: { random: random }
          })
        "
      >
        新增
      </a-button>
    </div>

    <!-- <a-card> -->
    <div class="tabel-wrapper">
      <standard-table
        :columns="columns"
        :dataSource="dataSource"
        @change="onChange"
        :pagination="pagination"
        size="large"
        :loading="loading"
      >
        <div slot="truly_time" slot-scope="{ text,record }">
          <template v-if="text != null" >
            <a style="text-decoration:underline;" @click="log_info(record.key)"  title='点击查看任务日志'>
           {{text}}
            </a>
          </template>
           <template v-else>
            <a style="text-decoration:underline;">
            暂未开始
            </a>
          </template>
        </div>
        <div slot="status" slot-scope="{ text }">
          <template v-if="text == 1">
            <a-tag
              style="
                width: 70px;
                height: 30px;
                text-align: center;
                line-height: 30px;
              "
              color="#2591FF"
            >
              待开始
            </a-tag>
          </template>
          <template v-else-if="text == 2">
            <a-tag
              style="
                width: 70px;
                height: 30px;
                text-align: center;
                line-height: 30px;
              "
              color="#FF6D25"
            >
              进行中
            </a-tag>
          </template>
          <template v-else-if="text == 3">
            <a-tag
              style="
                width: 70px;
                height: 30px;
                text-align: center;
                line-height: 30px;
              "
              color="#f5222d"
            >
              超时
            </a-tag>
          </template>
          <template v-else>
            <a-tag
              style="
                width: 70px;
                height: 30px;
                text-align: center;
                line-height: 30px;
              "
              color="#4E25FF"
            >
              测试验收
            </a-tag>
          </template>
        </div>
        <!-- eslint-disable-next-line -->
        <div slot="action" slot-scope="{ text, record }">
          <!-- {{ record.key }} -->

          <a
            v-if='userInfo.permissions.task_detail'
            :href="`#/task/detail?random=${random}&&id=${record.key}`"
            style="margin-right: 8px"
            >查看</a
          >
          <a
          v-if='userInfo.permissions.task_edit'
            :href="`#/task/add?random=${random}&&id=${record.key}`"
            style="margin-right: 8px"
            >| 编辑</a
          >
          <a-popconfirm
            v-if="record.status < 2  &&  userInfo.permissions.task_delete"
            title="确定删除该任务吗?"
            ok-text="是的"
            cancel-text="取消"
            @confirm="() => confirm(record.key)"
          >
            <a>| 删除</a>
          </a-popconfirm>
          <template v-if="text.engineer_id === userId && userInfo.permissions.task_start">
            <a href="">| </a>
            <a-popconfirm    
              title="确定开始此任务吗?"
              ok-text="是的"
              cancel-text="取消"
              v-if="!record.log_status || record.log_status == 3"
              @confirm="() => start_task(record.key)"
            >
              <a>
                <!-- {{ record.log_status }} -->
                <a-icon
                  style="margin-right: 5px"
                  type="play-circle"
                  title="开始"
                ></a-icon
              ></a>
            </a-popconfirm>
              <a>
                <a-icon
                   v-if="record.log_status == 1"
                @click='showPauseModal(record.key)'
                  type="pause-circle"
                  title="暂停"
                  style="margin-right: 5px"
                ></a-icon>
              </a>
                <a-modal
                  title="任务暂停备注"
                  destroyOnClose
                  :visible="pause_visible"
                  :confirm-loading="pause_confirmLoading"
                  @ok="() => pause_handleOk(record.key)"
                  @cancel="pause_handleCancel"
              >

              <a-form
                id="components-form-demo-normal-login"
                ref="pause_form"
                :form="pause_form"
                class="login-form"
                v-bind="{
                  labelCol: { span: 6 },
                  wrapperCol: { span: 14 }
                }"
              >
                <a-form-item label="任务暂停备注">
                  <a-textarea
                    v-decorator="[
                      'desc',
                      {
                        rules: [{ required: true, message: '此处填写任务暂停备注!' }]
                      }
                    ]"
                    placeholder="此处填写任务暂停备注"
                  >
                  </a-textarea>
                </a-form-item>
              </a-form>
                  </a-modal>     
                          <a>
                              <a-icon
                              @click="showSuspendModal(record.key)"
                                type="stop"
                                title="中止"
                                style="margin-right: 5px; color: #f5222d"
                              ></a-icon>
                            </a>
                          <a-modal
                            title="中止任务"
                            :visible="suspend_visible"
                            :confirm-loading="suspend_confirmLoading"
                            @ok="suspend_handleOk(record.key)"
                            @cancel="suspend_handleCancel"
                           >

                              <a-form
                                id="components-form-demo-normal-login"
                                ref="suspend_form"
                                :form="suspend_form"
                                class="login-form"
                                v-bind="{
                                  labelCol: { span: 6 },
                                  wrapperCol: { span: 14 }
                                }"
                              >
                                <a-form-item label="中止原因">
                                  <a-textarea
                                    v-decorator="[
                                      'desc',
                                      {
                                        rules: [{ required: true, message: '请备注任务中止原因!' }]
                                      }
                                    ]"
                                    placeholder="任务中止原因"
                                  >
                                  </a-textarea>
                                </a-form-item>
                              </a-form>
                            </a-modal>
            <a-popconfirm
              title="确定完成此任务吗?"
              ok-text="是的"
              cancel-text="取消"
                 @confirm="() =>finish_task(record.key,'完成任务')"
            >
              <a>
                <a-icon
                  type="check-circle"
                  title="完成"
                  style="margin-right: 5px"
                />
              </a>
            </a-popconfirm>
          </template>
        </div>
        <template slot="statusTitle">
          <a-icon @click.native="onStatusTitleClick" type="info-circle" />
        </template>
      </standard-table>
    </div>
     <a-modal v-model="log_visible" title="任务日志" ok-text="确认"  @ok="hideModal">
              <a-table :columns="log_columns" :data-source="log_data">
               
              </a-table>
          </a-modal>
    <!-- </a-card> -->
  </page-layout>
</template>

<script>
import PageLayout from "@/layouts/PageLayout";
import StandardTable from "@/components/table/StandardTable";
import {
  list,
  deleteItem,
  finish,
  suspend,
  pause,
  start,
  logs
} from "@/services/task";
import Cookie from "js-cookie";
// import { mapMutations } from "vuex";
const columns = [
  {
    title: "ID",
    dataIndex: "key"
  },
    {
    title: "关联需求",
    dataIndex: "requirement_name"
  },
  {
    title: "任务名称",
    dataIndex: "title"
  },
  {
    title: "工程师",
    dataIndex: "engineer_name"
  },
  {
    title: "对接人",
    dataIndex: "docking_name"
  },
  {
    title: "任务状态",
    dataIndex: "status",
    scopedSlots: { customRender: "status" }
  },
   {
    title: "总耗时",
    dataIndex: "truly_time" ,
    scopedSlots: { customRender: "truly_time" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
    align: "center"
  }
];
const log_columns = [

  {
    title: 'id',
    dataIndex: 'id',
    key: 'id',
      },
    {
    title: '开始时间',
    dataIndex: 'created_at',
    key: 'created_at',
    ellipsis: true,
  },
  {
    title: '备注内容',
    dataIndex: 'desc',
    key: 'desc',
    width: 120,
  },
  {
    title: '耗时',
    dataIndex: 'hours',
    scopedSlots: { customRender: "hours" } ,
    key:'hours' ,
    width: 120,
  }
  ,
  {
    title: '结束时间',
    dataIndex: 'end_at',
    key: 'end_at',
    ellipsis: true,
  },
];

export default {
  name: "demand",
  components: { PageLayout, StandardTable },
  data() {
    return {
      userInfo:[],
      log_columns ,
      log_visible:false,
      log_data:"" ,
      pause_visible:false ,
      pause_form: this.$form.createForm(this, { name: "desc" }),
      pause_confirmLoading:false ,
      suspend_visible:false ,
      suspend_form: this.$form.createForm(this, { name: "desc" }),
      suspend_confirmLoading:false ,
      userId: "",
      searchText: "",
      random: "",
      loading: true,
      desc: "需求管理中心",
      columns: columns,
      dataSource: [],
      selectedRows: [],
      pagination: {
        size: "small",
        showSizeChanger: true,
        showQuickJumper: true,
        poposition: "bottom",
        pageSize: 5,
        current: 1,
        total: 0
      }
    };
  },
  authorize: {
    deleteRecord: "delete"
  },
  activated() {
    const { pageSize, current } = this.pagination;
    this.random = Math.random();
    this.loadTableData({ limit: pageSize, page: current });
  },
  created() {
       let userInfo = JSON.parse(window.localStorage.getItem('admin.user'))
      this.userInfo = userInfo
    // 初始数据
    const { pageSize, current } = this.pagination;
    this.random = Math.random();
    this.loadTableData({ limit: pageSize, page: current });
  },
  mounted() {
    this.userId = +Cookie.get("Authorization").split(" ")[1];
    // console.log(typeof this.userId);
  },
  methods: {
    //日志弹窗控制方法
    hideModal() {
      this.log_visible = false;
    },
      log_info(id) {
         this.log_visible = true;
         logs(id).then(
            (res) => {
              console.log(res.data.data);
              if (res.data.code === 20000) {
                this.log_data = res.data.data ;
                  // this.$message.success(res.data.message);
                 setTimeout(() => {
                   const { pageSize, current } = this.pagination;
                    this.loadTableData({ limit: pageSize, page: current });
                  }, 100);
              }
            }
          ); 
    },
     start_task(id){
          start(id).then(
            (res) => {
              console.log(res.data.code);
              if (res.data.code === 20000) {
                this.$message.success(res.data.message);
                 setTimeout(() => {
                   const { pageSize, current } = this.pagination;
                    this.loadTableData({ limit: pageSize, page: current });
                  }, 500);
                
              }
            }
          );
     } ,
      finish_task(id,desc){
          finish({id,desc}).then(
            (res) => {
              console.log(res.data.code);
              if (res.data.code === 20000) {
                this.$message.success(res.data.message);
                setTimeout(() => {
                   const { pageSize, current } = this.pagination;
          this.loadTableData({ limit: pageSize, page: current });
                  }, 500);
                
              }
            }
        
        );
     } ,
      showSuspendModal(){
       this.suspend_visible = true;
    } ,
   
      suspend_handleOk(id) {
      this.suspend_form.validateFields((err, values) => {
        if (!err) {
          suspend({ id,...values}).then(
            (res) => {
              console.log(res.data.code);
              if (res.data.code === 20000) {
                this.$message.success(res.data.message);
                this.suspend_form.resetFields();
                 setTimeout(() => {
                     const { pageSize, current } = this.pagination;
                     this.loadTableData({ limit: pageSize, page: current });
                     this.suspend_visible = false;
                  }, 500);
                
              }
            }
          );
        }
      });
    },
      suspend_handleCancel() {
      // console.log('Clicked cancel button');
      this.suspend_visible = false;
    },
   showPauseModal(id){
        this.pauseid = id
        this.pause_visible = true
    },
     pause_handleOk() {
      this.pause_form.validateFields((err, values) => {
        if (!err) {
          pause({ id:this.pauseid,...values}).then(
            (res) => {
              console.log(res.data.code);
              if (res.data.code === 20000) {
                this.$message.success(res.data.message);
                this.pause_form.resetFields();
                 setTimeout(() => {
                     const { pageSize, current } = this.pagination;
                     this.loadTableData({ limit: pageSize, page: current });
                     this.pause_visible = false;
                  }, 1000);
                
              }
              
            }
          );
        }
      });
    },
       pause_handleCancel() {
      // console.log('Clicked cancel button');
      this.pause_visible = false;
    },
  
    // 请求table 的数据
    // obj 请求的字段
    loadTableData(obj) {
      this.loading = true;
      list(obj).then((res) => {
        // console.log(res.data, 222222);
        // 关闭loading
        this.loading = false;
        if (res.data.code === 20000) {
          const { current_page, total, per_page } = res.data.data;
          Object.assign(this.pagination, {
            total: parseInt(total),
            current: parseInt(current_page),
            pageSize: parseInt(per_page)
          }); 
          this.dataSource = res.data.data.data.map((item) => {
            // console.log(item);
            const {
              requirement_name,
              task_id,
              created_at,
              title,
              engineer_name,
              engineer_id,
              docking_name,
              docking_id,
              status,
              log_status,
              truly_time,
             
            
            } = item;
            return {
              key: task_id,
              requirement_name ,
              created_at: created_at && created_at.split(" ")[0],
              title: title || "未知",
              engineer_name: engineer_name || "未知",
              docking_name: docking_name || "未知",
              engineer_id,
              docking_id,
              status,
              log_status,
              truly_time,
          
            };
          });
        }
      });
    },
    handelsearch() {
      this.loadTableData({
        limit: this.pagination.pageSize,
        title: this.searchText
      });
      this.searchText = "";
    },

    onClear() {
      this.$message.info("您清空了勾选的所有行");
    },
    onStatusTitleClick() {
      this.$message.info("你点击了状态栏表头");
    },
    onChange(e) {
      // console.log(e);
      const { current, pageSize } = e;
      this.loadTableData({ limit: pageSize, page: current });
    },
    handleMenuClick(e) {
      if (e.key === "delete") {
        this.remove();
      }
    },
    cancel(key) {
      this.$message.info(`点击了取消,行数为${key + 1}行`);
    },
    confirm(key) {
      // 发起删除的请求
      deleteItem(key).then((res) => {
        // console.log(res, "delete");
        // 成功
        if (res.data.code === 20000) {
          // 提示信息
          this.$message.success({
            content: res.data.message || "删除成功~"
          });
          // 删除成功后重新获取数据
          const { pageSize, current } = this.pagination;
          this.loadTableData({ limit: pageSize, page: current });
        } else {
          this.$message.error(res.data.message || "删除失败！");
        }
      });
    },
  }
};
</script>

<style lang="less">
.search-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;

  > div {
    .search-input input {
      padding-left: 45px !important;
    }
    display: flex;
    width: 60%;
    .ant-input-affix-wrapper {
      display: inline-block;
      width: calc(100% - 150px);
      height: 54px !important;
      input {
        height: 100% !important;
      }
      input::-webkit-input-placeholder {
        color: #9999;
        font-size: 16px;
      }

      input::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: #9999;
        font-size: 16px;
      }

      input:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: #9999;
        font-size: 16px;
      }

      input:-ms-input-placeholder {
        /* Internet Explorer 10-11 */
        color: #9999;
        font-size: 16px;
      }
    }
    .search-button {
      margin-left: 30px;
      width: 120px;
      height: 54px;
    }
  }
}
.task {
  .tabel-wrapper {
    border-radius: 5px;
    // min-height: 450px;
    background-color: #fff;
    color: #1f1f1f;
    .ant-pagination {
      margin-top: 60px !important;
    }
    tr {
      height: 66px !important;
      // padding-left: 10px;
    }
    .ant-table-thead {
      padding-left: 20px;
      background: #effaff;
      & > tr > th {
        background: #effaff !important;
      }
    }
    .ant-table-tbody {
      padding-left: 20px;
    }
    .ant-table-pagination.ant-pagination {
      float: unset !important;
      text-align: center;
    }
  }
}
</style>
